package com.mp.ipm2020.admin.controller;


import com.mp.ipm2020.common.api.CommonPage;
import com.mp.ipm2020.common.api.CommonResult;
import com.mp.ipm2020.mbg.dto.UpdateUserPasswordParam;
import com.mp.ipm2020.mbg.dto.UserLoginParam;
import com.mp.ipm2020.mbg.dto.UserParam;
import com.mp.ipm2020.mbg.model.Role;
import com.mp.ipm2020.mbg.model.User;
import com.mp.ipm2020.mbg.service.RoleService;
import com.mp.ipm2020.mbg.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import sun.font.TrueTypeFont;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther adidasshe@mp.cn
 * <p>
 * 用户管理
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @ApiOperation(value = "登录返回token")
    @PostMapping("/login")
    public CommonResult login(@RequestBody UserLoginParam userLoginParam, BindingResult result) {
        String token = userService.login(userLoginParam.getUsername(), userLoginParam.getPassword());
        if (token == null) {
            return CommonResult.validateFailed("用户不可用或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation(value = "刷新token")
    @GetMapping("/refreshToken")
    public CommonResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = userService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation(value = "登出功能")
    @PostMapping("/logout")
    public CommonResult logout() {
        return CommonResult.success(null);
    }

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
//    @PreAuthorize("hasAnyAuthority('v1')") //拥有管理员权限的才能访问
    public CommonResult<User> register(@RequestBody UserParam userParam, BindingResult result) {
        User user = userService.register(userParam);
        if (user == null) {
            return CommonResult.failed("用户已存在");
        }
        return CommonResult.success(user);
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/info")
    public CommonResult getUserInfo(Principal principal) {
        if (principal == null) {
            return CommonResult.unauthorized(null);
        }
        String username = principal.getName();
        User user = userService.getUserByUsername(username);
        Map<String, Object> data = new HashMap<>();
        data.put("username", user.getUsername());
        data.put("roles", new String[]{"admin"});
        data.put("menus", roleService.getMenuList(user.getId()));
        data.put("icon", user.getIcon());
        return CommonResult.success(data);
    }

    @ApiOperation("获取指定用户信息")
    @GetMapping("/{id}")
    public CommonResult<User> getItem(@PathVariable Long id) {
        User user = userService.getById(id);
        return CommonResult.success(user);
    }

    @ApiOperation("根据用户名或姓名分页获取用户列表")
    @GetMapping("/list")
    public CommonResult<CommonPage<User>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                               @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                               @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        List<User> userList = userService.list(keyword, pageSize, pageNum);
//        userList.forEach(System.out::println);
        return CommonResult.success(CommonPage.restPage(userList));
    }

    @ApiOperation("修改指定用户信息")
    @PutMapping("/{id}")
    public CommonResult update(@PathVariable Long id, @RequestBody User user) {
        user.setPassword(null);
        boolean count = userService.updateById(user);
        if (count == true) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("修改指定用户密码")
    @PutMapping("/password")
    public CommonResult updatePassword(@RequestBody UpdateUserPasswordParam updatePasswordParam ) {
        int status = userService.updatePassword(updatePasswordParam);
        if (status > 0) {
            return CommonResult.success(status);
        } else if (status == -1) {
            return CommonResult.failed("提交参数不合法");
        } else if (status == -2) {
            return CommonResult.failed("找不到该用户");
        } else if (status == -3) {
            return CommonResult.failed("旧密码错误");
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("删除指定用户信息")
    @DeleteMapping("/{id}")
    public CommonResult delete(@PathVariable Long id) {

        if (id == 1) {
            return CommonResult.failed("默认账户不能删除");
        } else {
            boolean count = userService.removeById(id);
            if (count == true) {
                return CommonResult.success(count);
            }
            return CommonResult.failed();
        }
    }

    @ApiOperation("修改帐号状态")
    @PutMapping("/status/{id}")
    public CommonResult updateStatus(@PathVariable Long id, @RequestParam(value = "status") Integer status) {
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        boolean count = userService.updateStatusById(id, user);
        if (count == true) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("给用户分配角色")
    @PutMapping("/role")
    public CommonResult updateRole(@RequestParam("userId") Long userId,
                                   @RequestParam("roleIds") List<Long> roleIds) {
        System.out.println(userId + "=========>" + roleIds);
        boolean count = userService.updateRole(userId, roleIds);
        if (count == true) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("获取指定用户的角色")
    @GetMapping("/role/{userId}")
    public CommonResult<List<Role>> getRoleList(@PathVariable Long userId) {
        List<Role> roleList = userService.getRoleList(userId);
        return CommonResult.success(roleList);
    }


}
